package kz.kstu.shop.desktop.ui.frame;

import kz.kstu.shop.app.util.sync.SyncLocalManager;
import kz.kstu.shop.desktop.ui.form.ProductGuidePage;
import kz.kstu.shop.desktop.util.GUIUtils;
import org.apache.log4j.Logger;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author Filipp_Stankevich
 *         created: 25.07.11 20:40
 */
public class ApplicationFrame extends JFrame {

    private JMenuItem exitMenuItem;
    private JMenuItem goodsMenuItem;
    private JMenuItem syncMenuItem;

    public void initStaticComponents() {
        initMenuBar();
        initListeners();
        initWindow();
    }

    private void initMenuBar() {
        JMenuBar menuBar = new JMenuBar();

        JMenu fileMenu = new JMenu("Файл");
        exitMenuItem = new JMenuItem("Выход");
        fileMenu.add(exitMenuItem);

        JMenu guidesMenu = new JMenu("Справочники");
        goodsMenuItem = new JMenuItem("Номенклатура");
        guidesMenu.add(goodsMenuItem);

        JMenu serviceMenu = new JMenu("Сервисы");
        syncMenuItem = new JMenuItem("Синхронизация");
        serviceMenu.add(syncMenuItem);

        menuBar.add(fileMenu);
        menuBar.add(guidesMenu);
        menuBar.add(serviceMenu);
        this.setJMenuBar(menuBar);
    }

    private void initWindow() {
        this.setTitle("АРМ");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setSize(GUIUtils.preferredStartupScreenSize());
        this.setMinimumSize(GUIUtils.preferredStartupScreenSize());
    }

    private void initListeners() {
        final JFrame instance = this;
        exitMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                instance.dispose();
            }
        });

        goodsMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ProductGuidePage goodsPage = new ProductGuidePage();
                goodsPage.initStaticComponent();
                goodsPage.initData();
                instance.setContentPane(goodsPage.getRootPanel());
                instance.pack();
            }
        });

        syncMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        SyncLocalManager.getInstance().syncAll();
                    }
                };
                Thread thread = new Thread(runnable);
                thread.start();
            }
        });
    }
}
